package com.cloud.business.service.sys.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.business.dao.sys.SysRolePermissionMapper;
import com.cloud.business.entity.sys.SysRolePermission;
import com.cloud.business.model.commonvm.DataCheckFlag;
import com.cloud.business.model.commonvm.DeletePost;
import com.cloud.business.model.commonvm.ResultMsg;
import com.cloud.business.model.sys.sysrolepermissionvm.SysRolePermissionQueryModel;
import com.cloud.business.model.sys.sysrolepermissionvm.UpdateRolePermissionPost;
import com.cloud.business.service.sys.ISysRolePermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统角色权限关联表 服务实现类
 * </p>
 *
 * @author dh
 * @since 2020-03-21
 */
@Service
public class SysRolePermissionServiceImpl extends ServiceImpl<SysRolePermissionMapper, SysRolePermission> implements ISysRolePermissionService {

    private final SysRolePermissionMapper sysRolePermissionMapper;

    @Autowired
    public SysRolePermissionServiceImpl(SysRolePermissionMapper sysRolePermissionMapper) {
        this.sysRolePermissionMapper = sysRolePermissionMapper;
    }

    //region 获取分页列表

    /**
     * 获取分页列表
     *
     * @param SysRolePermissionQueryModel
     * @param page
     * @param msg
     * @throws Exception
     */
    @Override
    public void getListByPage(SysRolePermissionQueryModel SysRolePermissionQueryModel, IPage<SysRolePermission> page, ResultMsg msg) throws Exception {
        QueryWrapper<SysRolePermission> SysRolePermissionQueryWrapper = new QueryWrapper<>();
        SysRolePermissionQueryWrapper.lambda()
//                .like(!StringUtils.isEmpty(SysRolePermissionQueryModel.getQueryStr()), SysRolePermission::getName, SysRolePermissionQueryModel.getQueryStr())
                ;
        sysRolePermissionMapper.selectPage(page, SysRolePermissionQueryWrapper);
        msg.setMsg("获取成功");
    }
    //endregion

    //region 创建

    /**
     * 创建
     *
     * @param sysRolePermission
     * @param msg
     * @return
     * @throws Exception
     */
    @Override
    public Integer create(SysRolePermission sysRolePermission, ResultMsg msg) throws Exception {
        Date now = new Date();
        sysRolePermission.setCreateTime(now);
        sysRolePermission.setModificationTime(now);
        int count = sysRolePermissionMapper.insert(sysRolePermission);
        msg.setMsg("创建成功");
        return sysRolePermission.getObjectId();
    }
    //endregion

    //region 更新

    /**
     * 更新
     *
     * @param sysRolePermission
     * @param msg
     * @return
     * @throws Exception
     */
    @Override
    public Integer update(SysRolePermission sysRolePermission, ResultMsg msg) throws Exception {
        Date now = new Date();
        sysRolePermission.setModificationTime(now);
        int count = sysRolePermissionMapper.updateById(sysRolePermission);
        msg.setMsg("更新成功");
        return sysRolePermission.getObjectId();
    }
    //endregion

    //region 获取单条

    /**
     * 获取单条
     *
     * @param operationId
     * @param objectId
     * @param msg
     * @return
     * @throws Exception
     */
    @Override
    public SysRolePermission getById(Integer operationId, Integer objectId, ResultMsg msg) throws Exception {
        SysRolePermission sysRolePermission = sysRolePermissionMapper.selectById(objectId);
        msg.setMsg("获取成功");
        return sysRolePermission;
    }
    //endregion

    //region 批量删除

    /**
     * 批量删除
     *
     * @param deletePost
     * @param msg
     * @return
     * @throws Exception
     */
    @Override
    public int deleteByList(DeletePost deletePost, ResultMsg msg) throws Exception {
        msg.setMsg("删除成功");
        int count = sysRolePermissionMapper.deleteBatchIds(deletePost.getKeyValues());
        if (count <= 0) {
            throw new Exception("删除失败");
        }
        return count;
    }
    //endregion

    //region 角色权限设置or更新角色权限

    /**
     * 角色权限设置or更新角色权限
     *
     * @param updateRolePermissionPost
     * @param msg
     * @return
     * @throws Exception
     */
    @Override
    public Boolean updateRolePermissions(UpdateRolePermissionPost updateRolePermissionPost, ResultMsg msg) throws Exception {
        List<DataCheckFlag> dataCheckFlagList = updateRolePermissionPost.getDataChecks();
        if (dataCheckFlagList.size() <= 0) {
            throw new Exception("无修改数据");
        }
        QueryWrapper<SysRolePermission> sysRolePermissionQueryWrapper = new QueryWrapper<>();
        sysRolePermissionQueryWrapper.lambda()
                .eq(SysRolePermission::getRoleId, updateRolePermissionPost.getRoleId());
        List<SysRolePermission> sysRolePermissionList = sysRolePermissionMapper.selectList(sysRolePermissionQueryWrapper);
        List<Integer> alreadyPermissionIds = sysRolePermissionList.stream().map(SysRolePermission::getPermissionId).collect(Collectors.toList());

        List<SysRolePermission> sysRolePermissionAddList = new ArrayList<>();
        List<Integer> removePermissionIds = new ArrayList<>();
        Date now = new Date();

        dataCheckFlagList.forEach(item -> {
            if (item.isCheckFlag() && !alreadyPermissionIds.contains(item.getObjectId())) {
                SysRolePermission sysRolePermission = new SysRolePermission() {{
                    setIsDeleted(0);
                    setCreateTime(now);
                    setModificationTime(now);
                    setCreateUserId(updateRolePermissionPost.getOperationId());
                    setModificationUserId(updateRolePermissionPost.getOperationId());
                    setPermissionId(item.getObjectId());
                    setRoleId(updateRolePermissionPost.getRoleId());
                }};
                sysRolePermissionAddList.add(sysRolePermission);
            } else if (!item.isCheckFlag() && alreadyPermissionIds.contains(item.getObjectId())) {
                SysRolePermission sysRolePermission = sysRolePermissionList.stream().filter(o -> o.getPermissionId().equals(item.getObjectId()))
                        .findAny().orElse(null);
                if (sysRolePermission != null) {
                    removePermissionIds.add(sysRolePermission.getObjectId());
                }
            }
        });

        if (sysRolePermissionAddList.size() > 0) {
            //批量插入到数据库
            sysRolePermissionMapper.insertBatch(sysRolePermissionAddList);
        }
        if (removePermissionIds.size() > 0) {
            sysRolePermissionMapper.deleteBatchIds(removePermissionIds);
        }

        msg.setMsg("更新成功");
        return true;
    }
    //endregion

}
